/**
 * 项目中使用的图标，可按需加载
 * 支持，从URL中获取，支持Iconfont，支持本地图标等。
 */
import React from 'react';
import Icon from '@ant-design/icons';
import * as Icons from '@ant-design/icons';

// 参考 https://blog.csdn.net/xhwnous/article/details/90478979
const isUrl = (path: string): boolean => {
  if (!path.startsWith('http')) {
    return false;
  }
  try {
    const url = new URL(path);
    return !!url;
  } catch (error) {
    return false;
  }
};
/** 判断是否是图片链接 */
function isImg(path: string): boolean {
  return /\w.(png|jpg|jpeg|svg|webp|gif|bmp)$/i.test(path);
}

// Allow menu.js config icon as string or ReactNode
//   icon: 'setting',
//   icon: 'icon-geren' #For Iconfont ,
//   icon: 'http://demo.com/icon.png',
//   icon: '/favicon.png',
//   icon: <Icon type="setting" />,
const getIcon = (icon?: string | React.ReactNode): React.ReactNode => {
  if (typeof icon === 'string' && icon !== '') {
    if (isUrl(icon) || isImg(icon)) {
      return (
        <Icon component={() => <img src={icon} alt="icon" className="ant-pro-sider-menu-icon" />} />
      );
    }
    const NewIcon = Icons[icon] || Icons[`${icon}Outlined`];
    if (NewIcon) {
      try {
        return React.createElement(NewIcon);
      } catch (error) {
        return React.createElement(Icons.FileOutlined); // 默认
      }
    }
  }
  return icon;
};

/**
 * 根据文件扩展名获取文件图标
 * @param fileExt 文件扩展名
 * @returns
 */
const getFileIcon = (fileExt?: string): React.ReactNode => {
  const FileExtEnum = {
    xlsx: 'FileExcelOutlined',
    xls: 'FileExcelOutlined',
    doc: 'FileWordOutlined',
    docx: 'FileWordOutlined',
    jpg: 'FilejpgOutlined',
    jpeg: 'FilejpgOutlined',
  };
  let newFileExt = fileExt || 'File';
  if (newFileExt?.startsWith('.')) {
    newFileExt = newFileExt.substr(1);
  }
  const NewIcon = Icons[FileExtEnum[newFileExt]] || Icons.FileOutlined;
  if (NewIcon) {
    try {
      return React.createElement(NewIcon);
    } catch (error) {
      return React.createElement(Icons.FileOutlined); // 默认
    }
  }
  return React.createElement(Icons.FileOutlined);
};

export default getIcon;
export { getFileIcon, isUrl, isImg, Icons };
